<?php


namespace NanQi\Hope\Traits;


trait EncryptionTrait
{
    //SELECT AES_DECRYPT(UNHEX(phone),SUBSTR(UNHEX(SHA2('nanqi',512)),1,15)) FROM users;
    private function getAESKey() : string
    {
        $key = config('hope.db-aes-key', 'nanqi');
        $key = hex2bin(openssl_digest($key, 'sha512'));
        $key = substr($key, 0, 15);

        return $key;
    }

    /**
     * 解密
     * @param string $value
     * @return string
     */
    protected function decryptAttribute(string $value) : string
    {
        if ($value) {
            $value = openssl_decrypt(base64_encode(hex2bin($value)), 'aes-128-ecb', $this->getAESKey());
        }
        return $value;
    }

    /**
     * 加密
     * @param string $value
     * @return string
     */
    protected function encryptAttribute(string $value) : string
    {
        if ($value) {
            $value = bin2hex(base64_decode(openssl_encrypt($value, 'aes-128-ecb', $this->getAESKey())));
        }
        return $value;
    }
}